<template>
  <div class="lawyer-list-view">
    <el-card class="lawyer-header">
      <template #header>
        <div class="card-header">
          <h3>律师管理</h3>
          <div class="header-actions">
            <el-button type="success" @click="handleAdd">+ 新增律师</el-button>
            <el-button type="warning" @click="handleBatchSync">批量同步</el-button>
          </div>
        </div>
      </template>

      <el-form
        :model="queryForm"
        ref="queryFormRef"
        :inline="true"
        label-width="auto"
        class="search-form"
      >
        <el-form-item label="关键词" prop="keywords">
          <el-input
            id="lawyer-keywords"
            v-model="queryForm.keywords"
            placeholder="律师姓名/手机号"
            clearable
            @keyup.enter="handleSearch"
            class="search-input"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select
            id="lawyer-status"
            v-model="queryForm.status"
            placeholder="请选择状态"
            clearable
            class="search-select"
          >
            <el-option label="正常" value="1"></el-option>
            <el-option label="禁用" value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-select
            id="lawyer-type"
            v-model="queryForm.type"
            placeholder="请选择类型"
            clearable
            class="search-select"
          >
            <el-option
              v-for="(item, key) in LawyerTypeMap"
              :key="key"
              :value="key"
              :label="item.label"
            />
          </el-select>
        </el-form-item>
        <el-form-item class="search-buttons">
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="lawyer-content">
      <el-table
        :data="lawyerList"
        border
        v-loading="loading"
        style="width: 100%"
        class="lawyer-table"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="律师姓名" width="120" />
        <el-table-column prop="type" label="类型" width="100">
          <template #default="scope">
            {{ LawyerTypeMap[scope.row.type as LawyerType]?.label || '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="username" label="用户名" width="120" />
        <el-table-column prop="firm_name" label="所属律所" min-width="150" show-overflow-tooltip />
        <el-table-column prop="mobile" label="手机号" width="120" />
        <el-table-column prop="province" label="省份" width="100" />
        <el-table-column prop="city" label="城市" width="100" />
        <el-table-column prop="entry_time" label="首次执业" width="120">
          <template #default="scope">
            {{ formatDate(scope.row.entry_time) }}
          </template>
        </el-table-column>
        <el-table-column prop="create_time" label="创建时间" width="160">
          <template #default="scope">
            {{ formatDate(scope.row.create_time) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="80">
          <template #default="scope">
            <el-tag :type="LawyerStatusMap[scope.row.status as LawyerStatus]?.type || 'default'">
              {{ LawyerStatusMap[scope.row.status as LawyerStatus]?.label || '未知' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="can_login" label="登录权限" width="100">
          <template #default="scope">
            <el-switch
              :model-value="scope.row.can_login === 1"
              :active-value="true"
              :inactive-value="false"
              @change="(val: boolean) => handleToggleLoginPermission(scope.row, val ? 1 : 0)"
              :disabled="scope.row.admin_id > 0 || updatingRowId === scope.row.id"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right" class="table-action-column">
          <template #default="scope">
            <el-button size="small" @click="handleView(scope.row)">查看</el-button>
            <el-dropdown>
              <el-button size="small" type="primary" link>
                更多
                <el-icon><ArrowDown /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="edit" @click="() => handleCommand('edit', scope.row)">
                    编辑
                  </el-dropdown-item>
                  <el-dropdown-item
                    command="disable"
                    @click="() => handleCommand('disable', scope.row)"
                    v-if="scope.row.status === LawyerStatus.ENABLED"
                  >
                    禁用
                  </el-dropdown-item>
                  <el-dropdown-item
                    command="enable"
                    @click="() => handleCommand('enable', scope.row)"
                    v-if="scope.row.status === LawyerStatus.DISABLED"
                  >
                    启用
                  </el-dropdown-item>
                  <el-dropdown-item
                    command="sync"
                    @click="() => handleCommand('sync', scope.row)"
                    v-if="scope.row.can_login === 1 && !scope.row.admin_id"
                  >
                    同步到用户系统
                  </el-dropdown-item>
                  <el-dropdown-item
                    command="reset_password"
                    @click="() => handleCommand('reset_password', scope.row)"
                    v-if="scope.row.can_login === 1"
                  >
                    重置密码
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="queryForm.page"
          v-model:page-size="queryForm.limit"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 律师详情抽屉 - 使用GlobalDrawer组件 -->
    <GlobalDrawer
      v-model="detailDrawerVisible"
      :title="drawerTitle"
      size="60%"
      :before-close="handleBeforeClose"
      @confirm="handleSave"
      @cancel="handleDrawerClose"
      :show-footer-buttons="!isFormReadOnly"
    >
      <template #default>
        <div class="drawer-content">
          <el-form :model="detailForm" :rules="detailRules" ref="detailFormRef" label-width="120px">
            <!-- 基本信息 -->
            <el-divider content-position="left">基本信息</el-divider>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="登录用户名" prop="username">
                  <el-input
                    id="lawyer-username"
                    v-model="detailForm.username"
                    placeholder="请输入登录用户名"
                    :disabled="isFormReadOnly || detailForm.id > 0"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="律师姓名" prop="name">
                  <el-input
                    id="lawyer-name"
                    v-model="detailForm.name"
                    placeholder="请输入律师姓名"
                    :disabled="isFormReadOnly"
                  />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20" v-if="!detailForm.id">
              <el-col :span="12">
                <el-form-item label="登录密码" prop="password">
                  <el-input
                    id="lawyer-password"
                    v-model="detailForm.password"
                    placeholder="请输入登录密码"
                    type="password"
                    :disabled="isFormReadOnly"
                    show-password
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </template>
    </GlobalDrawer>

    <!-- 重置密码对话框 -->
    <el-dialog v-model="resetPasswordDialogVisible" title="重置密码" width="500px">
      <el-form
        :model="resetPasswordForm"
        :rules="resetPasswordRules"
        ref="resetPasswordFormRef"
        label-width="100px"
      >
        <el-form-item label="新密码" prop="password">
          <el-input
            v-model="resetPasswordForm.password"
            type="password"
            placeholder="请输入新密码"
            show-password
          />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirm_password">
          <el-input
            v-model="resetPasswordForm.confirm_password"
            type="password"
            placeholder="请再次输入新密码"
            show-password
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="resetPasswordDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleResetPasswordConfirm">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 批量同步对话框 -->
    <BatchSyncLawyers v-model="batchSyncVisible" @sync-success="handleSyncSuccess" />
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive, computed, onMounted } from 'vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import { ArrowDown, Close, Edit, Plus, View } from '@element-plus/icons-vue'
  import { GlobalDrawer } from '@/components/common'
  import BatchSyncLawyers from './components/BatchSyncLawyers.vue'
  import { lawyerApi } from '@/api/lawyer'
  import type { ApiResponse } from '@/types/api'
  import {
    Lawyer,
    LawyerType,
    LawyerTypeMap,
    LawyerStatus,
    LawyerStatusMap,
    Gender,
    GenderMap,
    Lawfirm,
  } from '../../types/lawyer'
  import { useLawyerStore } from '@/store/lawyer'

  // 定义律师查询表单接口
  interface LawyerQueryForm {
    page: number
    limit: number
    keywords: string
    status: string
    type: string
  }

  // 使用律师管理store
  const lawyerStore = useLawyerStore()

  // 日期格式化函数
  const formatDate = (timestamp: number | string) => {
    if (!timestamp) return ''
    const date = new Date(Number(timestamp) * 1000)
    return (
      date.getFullYear() +
      '-' +
      String(date.getMonth() + 1).padStart(2, '0') +
      '-' +
      String(date.getDate()).padStart(2, '0')
    )
  }

  // 日期时间格式化函数 (包含时分秒)
  const formatDateTime = (timestamp: number | string) => {
    if (!timestamp) return ''
    const date = new Date(Number(timestamp) * 1000)
    return (
      date.getFullYear() +
      '-' +
      String(date.getMonth() + 1).padStart(2, '0') +
      '-' +
      String(date.getDate()).padStart(2, '0') +
      ' ' +
      String(date.getHours()).padStart(2, '0') +
      ':' +
      String(date.getMinutes()).padStart(2, '0') +
      ':' +
      String(date.getSeconds()).padStart(2, '0')
    )
  }

  // 查询表单
  const queryForm = reactive({
    page: 1,
    limit: 10,
    keywords: '',
    status: '',
    type: '',
  })

  // 详情表单
  const detailForm = reactive({
    id: 0,
    firmid: '',
    name: '',
    username: '',
    password: '',
    confirm_password: '',
    pwd: '',
    salt: '',
    email: '',
    mobile: '',
    sex: Gender.MALE,
    thumb: '',
    type: LawyerType.REGISTERED,
    idcard: '',
    lawyer_license: '',
    provinceid: '',
    cityid: '',
    distid: '',
    education: '',
    honor: '',
    adept: '',
    desc: '',
    address: '',
    entry_time: '',
    create_time: 0,
    update_time: 0,
    last_login_time: 0,
    login_num: 0,
    last_login_ip: '',
    status: LawyerStatus.ENABLED,
    can_login: 0,
    admin_id: 0,
    region: {
      provinceid: '',
      cityid: '',
      distid: '',
    },
  })

  // 表单验证规则
  const detailRules = {
    username: [
      { required: true, message: '请输入登录用户名', trigger: 'blur' },
      { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' },
    ],
    password: [
      {
        required: true,
        message: '请输入登录密码',
        trigger: 'blur',
        validator: (rule: any, value: string, callback: Function) => {
          if (!detailForm.id && !value) {
            callback(new Error('请输入登录密码'))
          } else {
            callback()
          }
        },
      },
      { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' },
    ],
    confirm_password: [
      {
        required: true,
        message: '请再次输入登录密码',
        trigger: 'blur',
        validator: (rule: any, value: string, callback: Function) => {
          if (!detailForm.id && !value) {
            callback(new Error('请再次输入登录密码'))
          } else if (value !== detailForm.password) {
            callback(new Error('两次输入密码不一致'))
          } else {
            callback()
          }
        },
      },
    ],
    name: [
      { required: true, message: '请输入律师姓名', trigger: 'blur' },
      { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' },
    ],
    firmid: [{ required: true, message: '请选择执业律所', trigger: 'change' }],
    sex: [{ required: true, message: '请选择性别', trigger: 'change' }],
    mobile: [
      { required: true, message: '请输入手机号码', trigger: 'blur' },
      { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' },
    ],
    type: [{ required: true, message: '请选择执业类型', trigger: 'change' }],
    email: [
      { required: true, message: '请输入电子邮箱', trigger: 'blur' },
      { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' },
    ],
    entry_time: [{ required: true, message: '请选择首次执业日期', trigger: 'change' }],
    idcard: [
      { required: true, message: '请输入律师执业证号码', trigger: 'blur' },
      { min: 5, max: 50, message: '长度在 5 到 50 个字符', trigger: 'blur' },
    ],
    status: [{ required: true, message: '请选择状态', trigger: 'change' }],
    address: [{ required: true, message: '请输入详细地址', trigger: 'blur' }],
    education: [{ max: 100, message: '长度不超过 100 个字符', trigger: 'blur' }],
    adept: [{ max: 200, message: '长度不超过 200 个字符', trigger: 'blur' }],
    honor: [{ max: 200, message: '长度不超过 200 个字符', trigger: 'blur' }],
    desc: [{ max: 500, message: '长度不超过 500 个字符', trigger: 'blur' }],
  }

  // 数据相关
  const lawyerList = ref<Lawyer[]>([])
  const total = ref<number>(0)
  const loading = ref<boolean>(false)

  // 抽屉相关
  const detailDrawerVisible = ref<boolean>(false)
  const drawerTitle = ref<string>('新增律师')
  const isFormReadOnly = ref<boolean>(false) // 默认设置为可编辑状态

  // 批量同步对话框
  const batchSyncVisible = ref<boolean>(false)

  // 选项数据
  const lawfirmOptions = ref<Lawfirm[]>([])
  const provinceOptions = ref<any[]>([])
  const cityOptions = ref<any[]>([])

  // 表单引用
  const detailFormRef = ref()
  const queryFormRef = ref()

  // 处理地区选择变化
  const handleRegionChange = (region: any) => {
    // 将地区信息同步到表单字段
    detailForm.region.provinceid = region.provinceid
    detailForm.region.cityid = region.cityid
  }

  // 查询律师列表
  const loadLawyerList = async () => {
    loading.value = true
    // 清除正在更新状态，防止重复触发
    updatingRowId.value = null

    try {
      const response = await lawyerStore.getLawyerListAction(queryForm)
      if (response.code === 0) {
        // 处理数据，确保字段类型正确
        const processedData = response.data.map((item: any) => {
          return {
            ...item,
            entry_time: Number(item.entry_time) || 0,
            create_time: Number(item.create_time) || 0,
            update_time: Number(item.update_time) || 0,
            last_login_time: Number(item.last_login_time) || 0,
            login_num: Number(item.login_num) || 0,
            provinceid: Number(item.provinceid) || 0,
            cityid: Number(item.cityid) || 0,
            distid: Number(item.distid) || 0,
            firmid: Number(item.firmid) || 0,
            // 处理字段映射
            idcard: item.idcard || item.id_number || '',
            lawfirm: item.lawfirm || item.lawfirm_name || '',
          }
        })
        lawyerList.value = processedData
        total.value = response.count
      } else {
        ElMessage.error(response.msg || '获取律师列表失败')
      }
    } catch (error) {
      ElMessage.error('获取律师列表失败')
    } finally {
      loading.value = false
    }
  }

  // 搜索
  const handleSearch = () => {
    queryForm.page = 1
    loadLawyerList()
  }

  // 重置
  const handleReset = () => {
    queryForm.keywords = ''
    queryForm.status = ''
    queryForm.type = ''
    queryForm.page = 1
    loadLawyerList()
  }

  // 添加律师
  const handleAdd = () => {
    drawerTitle.value = '新增律师'
    // 重置表单
    isFormReadOnly.value = false // 新增律师时设置为可编辑状态
    Object.assign(detailForm, {
      id: 0,
      firmid: '',
      name: '',
      username: '',
      password: '',
      confirm_password: '',
      pwd: '',
      salt: '',
      email: '',
      mobile: '',
      sex: Gender.MALE,
      thumb: '',
      type: LawyerType.REGISTERED,
      idcard: '',
      lawyer_license: '',
      provinceid: '',
      cityid: '',
      distid: '',
      education: '',
      honor: '',
      adept: '',
      desc: '',
      address: '',
      entry_time: '',
      create_time: 0,
      update_time: 0,
      last_login_time: 0,
      login_num: 0,
      last_login_ip: '',
      status: LawyerStatus.ENABLED,
      can_login: 1,
      admin_id: 0,
      region: {
        provinceid: '',
        cityid: '',
        distid: '',
      },
    })
    detailDrawerVisible.value = true
  }

  // 查看律师详情
  const handleView = (row: Lawyer) => {
    drawerTitle.value = '查看律师'
    isFormReadOnly.value = true // 设置为只读状态
    Object.assign(detailForm, row)
    // 同步地区信息到region对象，确保类型匹配
    detailForm.region = {
      provinceid: String(row.provinceid || ''),
      cityid: String(row.cityid || ''),
      distid: String(row.distid || ''),
    }
    detailDrawerVisible.value = true
  }

  // 添加编辑按钮处理函数
  const handleEditClick = () => {
    isFormReadOnly.value = false // 设置为可编辑状态
    drawerTitle.value = '编辑律师' // 更新抽屉标题
  }

  // 编辑律师
  const handleEdit = (row: Lawyer) => {
    drawerTitle.value = '编辑律师'
    isFormReadOnly.value = false // 编辑律师时设置为可编辑状态
    Object.assign(detailForm, row)
    // 同步地区信息到region对象，确保类型匹配
    detailForm.region = {
      provinceid: String(row.provinceid || ''),
      cityid: String(row.cityid || ''),
      distid: String(row.distid || ''),
    }
    detailDrawerVisible.value = true
  }

  // 保存律师
  const handleSave = async () => {
    if (!detailFormRef.value) return

    try {
      // 表单验证
      await detailFormRef.value.validate()

      // 处理数据格式，匹配后端API要求
      const formData: any = {
        id: detailForm.id || 0,
        username: detailForm.username,
        name: detailForm.name,
        lawfirm_id: detailForm.firmid ? Number(detailForm.firmid) : 0,
        mobile: detailForm.mobile,
        sex: detailForm.sex,
        email: detailForm.email || '',
        idcard: detailForm.idcard || '',
        lawyer_license: detailForm.lawyer_license || '',
        education: detailForm.education || '',
        honor: detailForm.honor || '',
        adept: detailForm.adept || '',
        desc: detailForm.desc || '',
        provinceid: detailForm.region.provinceid ? Number(detailForm.region.provinceid) : 0,
        cityid: detailForm.region.cityid ? Number(detailForm.region.cityid) : 0,
        distid: detailForm.region.distid ? Number(detailForm.region.distid) : 0,
        type: detailForm.type,
        qualification_date: detailForm.entry_time
          ? Math.floor(new Date(detailForm.entry_time).getTime() / 1000)
          : 0,
        status: detailForm.status,
        can_login: detailForm.can_login,
      }

      // 新建律师时添加密码参数
      if (!detailForm.id && detailForm.password) {
        formData.password = detailForm.password
      }

      let response: ApiResponse<any>
      if (detailForm.id && detailForm.id > 0) {
        // 编辑模式
        response = await lawyerStore.editLawyerAction(formData)
      } else {
        // 新增模式
        response = await lawyerStore.addLawyerAction(formData)
      }

      if (response.code === 0) {
        ElMessage.success(response.msg || '保存成功')
        handleEditSuccess()
      } else {
        ElMessage.error(response.msg || '保存失败')
      }
    } catch (error) {
      // 表单验证失败或其他错误
      console.error('保存失败:', error)
      ElMessage.error('保存失败')
    }
  }

  // 禁用律师
  const handleDisable = (row: Lawyer) => {
    ElMessageBox.confirm(`确定要禁用律师【${row.name}】吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
      .then(async () => {
        try {
          const response: ApiResponse<any> = await lawyerStore.setLawyerStatusAction({
            type: 0,
            ids: row.id,
          })
          if (response.code === 0) {
            ElMessage.success(response.msg || '禁用成功')
            loadLawyerList()
          } else {
            ElMessage.error(response.msg || '禁用失败')
          }
        } catch (error) {
          ElMessage.error('禁用失败')
        }
      })
      .catch(() => {
        // 用户取消操作
      })
  }

  // 启用律师
  const handleEnable = (row: Lawyer) => {
    ElMessageBox.confirm(`确定要启用律师【${row.name}】吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
      .then(async () => {
        try {
          const response: ApiResponse<any> = await lawyerStore.setLawyerStatusAction({
            type: 1,
            ids: row.id,
          })
          if (response.code === 0) {
            ElMessage.success(response.msg || '启用成功')
            loadLawyerList()
          } else {
            ElMessage.error(response.msg || '启用失败')
          }
        } catch (error) {
          ElMessage.error('启用失败')
        }
      })
      .catch(() => {
        // 用户取消操作
      })
  }

  // 处理下拉菜单命令
  const handleCommand = (command: string, row?: Lawyer) => {
    switch (command) {
      case 'edit':
        handleEdit(row!)
        break
      case 'disable':
        handleDisable(row!)
        break
      case 'enable':
        handleEnable(row!)
        break
      case 'sync':
        handleSyncToUser(row!)
        break
      case 'reset_password':
        handleResetPassword(row!)
        break
    }
  }

  // 重置密码对话框相关
  const resetPasswordDialogVisible = ref<boolean>(false)
  const resetPasswordFormRef = ref()

  // 重置密码表单
  const resetPasswordForm = reactive({
    id: 0,
    password: '',
    confirm_password: '',
  })

  // 重置密码表单验证规则
  const resetPasswordRules = {
    password: [
      { required: true, message: '请输入新密码', trigger: 'blur' },
      { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' },
    ],
    confirm_password: [
      { required: true, message: '请再次输入新密码', trigger: 'blur' },
      {
        validator: (rule: any, value: string, callback: Function) => {
          if (value !== resetPasswordForm.password) {
            callback(new Error('两次输入密码不一致'))
          } else {
            callback()
          }
        },
        trigger: 'blur',
      },
    ],
  }

  // 重置密码处理
  const handleResetPassword = (row: Lawyer) => {
    resetPasswordForm.id = row.id
    resetPasswordForm.password = ''
    resetPasswordForm.confirm_password = ''
    resetPasswordDialogVisible.value = true
  }

  // 确认重置密码
  const handleResetPasswordConfirm = async () => {
    if (!resetPasswordFormRef.value) return

    await resetPasswordFormRef.value.validate(async (valid: boolean) => {
      if (valid) {
        try {
          const response = await lawyerStore.resetLawyerPasswordAction({
            id: resetPasswordForm.id,
            password: resetPasswordForm.password,
          })

          if (response.code === 0) {
            ElMessage.success('密码重置成功')
            resetPasswordDialogVisible.value = false
          } else {
            ElMessage.error(response.msg || '密码重置失败')
          }
        } catch (error) {
          ElMessage.error('密码重置失败')
        }
      }
    })
  }

  // 处理抽屉关闭
  const handleDrawerClose = () => {
    detailDrawerVisible.value = false
  }

  // 处理抽屉关闭前的确认
  const handleBeforeClose = (): boolean => {
    // 如果表单有修改，可以在这里添加确认提示
    // 这里简单返回true表示允许关闭
    return true
  }

  // 处理编辑成功
  const handleEditSuccess = () => {
    // 关闭编辑表单
    detailDrawerVisible.value = false

    // 刷新律师列表
    loadLawyerList()
  }

  // 分页相关
  const handleSizeChange = (val: number) => {
    queryForm.limit = val
    queryForm.page = 1
    loadLawyerList()
  }

  const handleCurrentChange = (val: number) => {
    queryForm.page = val
    loadLawyerList()
  }

  // 加载律所列表
  const loadLawfirmList = async () => {
    try {
      const response: ApiResponse<Lawfirm[]> = await lawyerStore.getLawfirmListAction({
        page: 1,
        limit: 1000,
      })
      if (response.code === 0) {
        lawfirmOptions.value = response.data
      } else {
        ElMessage.error(response.msg || '获取律所列表失败')
      }
    } catch (error) {
      ElMessage.error('获取律所列表失败')
    }
  }

  // 标记正在更新的行ID，防止重复触发
  const updatingRowId = ref<number | null>(null)

  // 切换登录权限
  const handleToggleLoginPermission = async (row: Lawyer, val: number) => {
    // 如果在初始化加载中或当前行正在更新中，则不做处理
    if (isInitialLoading.value || updatingRowId.value === row.id) return

    // 标记当前行为更新中
    updatingRowId.value = row.id

    try {
      const response = await lawyerStore.setLawyerLoginPermissionAction({
        id: row.id,
        can_login: val,
      })

      if (response.code === 0) {
        ElMessage.success(response.msg || '登录权限更新成功')
        // 手动更新用户数据，而不是通过v-model自动更新
        row.can_login = val
      } else {
        ElMessage.error(response.msg || '登录权限更新失败')
      }
    } catch (error) {
      ElMessage.error('登录权限更新失败')
    } finally {
      // 无论成功失败，都清除更新状态
      updatingRowId.value = null
    }
  }

  // 同步律师到用户系统
  const handleSyncToUser = async (row: Lawyer) => {
    try {
      const response = await lawyerStore.syncLawyerToUserAction({
        lawyer_id: row.id,
      })

      if (response.code === 0) {
        ElMessage.success(response.msg || '同步成功')
        loadLawyerList()
      } else {
        ElMessage.error(response.msg || '同步失败')
      }
    } catch (error) {
      ElMessage.error('同步失败')
    }
  }

  // 打开批量同步对话框
  const handleBatchSync = () => {
    batchSyncVisible.value = true
  }

  // 处理同步成功
  const handleSyncSuccess = () => {
    loadLawyerList()
  }

  // 初始化加载
  const isInitialLoading = ref(true) // 添加标记控制初始加载状态

  onMounted(() => {
    loadLawyerList().then(() => {
      // 列表加载完成后，设置初始加载状态为完成
      setTimeout(() => {
        isInitialLoading.value = false
      }, 500) // 给其一个延迟，确保所有组件都已渲染完成
    })
    loadLawfirmList()
  })
</script>

<style scoped>
  .lawyer-list-view {
    padding: 20px;
  }

  .lawyer-content {
    margin-bottom: 20px;
  }

  .lawyer-table {
    margin-top: 20px;
  }

  .dialog-footer {
    display: flex;
    justify-content: flex-end;
    margin-top: 20px;
  }

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0;
  }

  .card-header h3 {
    margin: 0;
    font-size: 16px;
    font-weight: 500;
  }

  .header-actions {
    display: flex;
    gap: 10px;
  }

  .drawer-content {
    padding: 0;
    height: 100%;
    overflow-y: auto;
  }

  /* 按钮样式 */
  .confirm-btn {
    background: linear-gradient(to right, #67c23a, #85ce61);
    border-color: #67c23a;
    transition: all 0.3s ease;
  }

  .confirm-btn:hover {
    background: linear-gradient(to right, #5daf34, #79ba57);
  }

  .edit-btn {
    background: linear-gradient(to right, #e6a23c, #ebb563);
    border-color: #e6a23c;
    transition: all 0.3s ease;
  }

  .edit-btn:hover {
    background: linear-gradient(to right, #d6962c, #e0a850);
    box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
  }

  .close-btn {
    background: linear-gradient(to right, #409eff, #66b1ff);
    border-color: #409eff;
    transition: all 0.3s ease;
  }

  .close-btn:hover {
    background: linear-gradient(to right, #3a8ee6, #5ca8ff);
    box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
  }

  .form-tip {
    margin-left: 10px;
    color: #909399;
    font-size: 12px;
  }

  :deep(.el-row) {
    margin-bottom: 5px;
  }

  :deep(.el-row:last-child) {
    margin-bottom: 0;
  }

  @media screen and (max-width: 768px) {
    .drawer-content {
      padding: 15px;
    }

    .search-form {
      flex-direction: column;
      gap: 15px;
    }

    .search-form .el-form-item:last-child {
      margin-left: 0;
    }
  }
</style>
